// import "./WavePointer.js"
(() => {
  const SET_POINTS = Symbol('SET_POINTS');
  const IS_ANIMATION = Symbol('IS_ANIMATION'); // 正在动画中，作为动画启动与停止的标志
  const ORIGIN_C = Symbol("ORIGIN_C"); // 原始 C 值

  class Wave {
    points = [];
    [IS_ANIMATION] = false;
  
    constructor (x = 0, y = 0, param) {
      let {
        count = 1, // 波点数量
        derta = 1, // 点间隔
        color = 'black', // 波点颜色
        wpr = 1, // 波点半径
        wpz = 0, // 波点z坐标
        a = 1, b = 1, c = 0, d = 0// y = a * sin(b * (x + c)) + d;
      } = param;
      this.count = count;
      this.derta = derta;
      this.color = color;
      this.wpr = wpr;
      this.wpz = wpz;
      this.a = a; this.b = b; this.c = c; this.d = d;
      this.x = x;
      this.y = y;
      this[ORIGIN_C] = c;
      this[SET_POINTS]();
    }
  
    // 生成波点数组
    [SET_POINTS] () {
      this.points = [];
      let halfCount = Math.floor(this.count / 2);
      for(let i = -halfCount; i < halfCount; i += 1) {
        let x = this.x + i * this.derta,
            y = this.a * Math.sin((this.b * x + this.c) / 180 * Math.PI) + this.d
        this.points.push(new WavePoint(x, y, this.wpz, this.wpr))
      }
    }

    // 绘制波点
    draw (ctx, points = this.points) {
      ctx.save();
      ctx.fillStyle = this.color;
      ctx.shadowColor = this.color;
      for(let i = 0; i < points.length; i += 1) {
        this.points[i].draw(ctx);
      }
      ctx.restore();
    }

    // 更新
    update (ob, deg) {
      this[SET_POINTS]();
      for(let i = 0; i < this.points.length; i += 1) {
        let wp = this.points[i];
        this.c += .05;
        if(this.c > 10000) this.c = this[ORIGIN_C];
        wp.x = wp.x * Math.cos(ator(deg)) - wp.z * Math.sin(ator(deg));
        wp.y = this.a * Math.sin((this.b * wp.originX + this.c) / 180 * Math.PI) + this.d;
        wp.z = wp.z * Math.cos(ator(deg)) + wp.x * Math.sin(ator(deg));

        wp.drawX = (wp.x - ob.x) * ob.z / (ob.z - wp.z);
        wp.drawY = (wp.y - ob.y) * ob.z / (ob.z - wp.z);
      }
    }

    // 启动动画
    startAni (cb = () => {}) {
      if(this[IS_ANIMATION]) return this;
      this[IS_ANIMATION] = true;
      const animate = () => {
        let id = requestAnimationFrame(animate);
        cb();
        if(!this[IS_ANIMATION]) cancelAnimationFrame(id);
      }
      animate();
    }

    // 停止动画
    endAni () {
      this[IS_ANIMATION] = false;
    }
  }

  window.Wave = Wave;
})()